<?php
//
// interact with database
//
class User_model extends CI_Model {

	//login table
	public $m_dbTableName	= "login";
	public $m_dbUser		= "username";
	public $m_dbPass		= "password";
	public $m_dbEmail		= "email";
	public $m_dbLevel		= "level";

	public function __construct()
	{
		parent::__construct();
	}

	public function db_verify_user($a_user, $a_pass)
	{
		$q = $this
				->db 
				->where($this->m_dbUser, $a_user)
				->where($this->m_dbPass, $a_pass)
				->limit(1)
				->get($this->m_dbTableName);

		if ($q->num_rows() > 0 ){
			//echo "<pre>";
			//print_r($q->row()) ;
			//echo "</pre>";
			return $q->row();
		}
		return FALSE;
	}

	public function db_get_userlist()
	{
		$q = $this
				->db 
				->get($this->m_dbTableName);

		// echo "<pre>";
		// print_r($q->result()) ;
		// echo "</pre>";
		return $q->result();
	}

	public function db_add_new_user($a_user, $a_pass,$a_email,$a_level)
	{
		// try to find unique ID
		$res = $this->db_get_row_from_user($a_user);
		if ($res == FALSE)
		{

			$data = array(
					$this->m_dbUser => $a_user,
					$this->m_dbPass => $a_pass,
					$this->m_dbEmail => $a_email,
					$this->m_dbLevel => $a_level
	            );
			$this->db->insert($this->m_dbTableName, $data);	
			return TRUE;
		}
		return FALSE;
	}

	public function db_update_user($a_id, $a_user, $a_pass, $a_email, $a_level)
	{
		$isOK = TRUE;
		if ($a_id != $a_user)
		{
			//check if new name is existing
			$res = $this->db_get_row_from_user($a_user);
			if ($res != FALSE)
			{
				$isOK = FALSE;
				return FALSE;
			}
		}

		if ($isOK)
		{
			$data = array(
				$this->m_dbUser => $a_user,
				$this->m_dbPass=> $a_pass,
				$this->m_dbEmail=> $a_email,
				$this->m_dbLevel => $a_level
            );
		
			$this->db->where($this->m_dbUser, $a_id);
			$this->db->update($this->m_dbTableName, $data);
			return TRUE;
		}
	}

	public function db_delete_user($a_user)
	{
		$q = $this->db->where($this->m_dbUser, $a_user);
		$q = $this->db->delete($this->m_dbTableName);
		return TRUE;
	}

	public function db_get_row_from_user($a_user)
	{
		$q = $this
				->db 
				->where($this->m_dbUser, $a_user)
				->limit(1)
				->get($this->m_dbTableName);
		
		if ($q->num_rows() > 0 ){
			// echo "<pre>";
			// print_r($q->row()) ;
			// echo "</pre>";
			return $q->row();
		}
		return FALSE;

	}

}
?>
